import {
  getItemsByItemType,
  deleteItem,
  postItem,
  putItem,
  getItemByTitleLike,
} from '../../../services/api';

export default {
  namespace: 'commodity',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *fetch({ payload: currentPage }, { call, put }) {
      const response = yield call(getItemsByItemType, 'commodities', currentPage);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *add({ payload, callback }, { call, put }) {
      const response = yield call(postItem, payload);
      yield put({
        type: 'append',
        payload: response,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const { id, currentIndex } = payload;
      yield call(deleteItem, id);
      yield put({
        type: 'delete',
        payload: currentIndex,
      });
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(putItem, payload.id, payload);
      yield put({
        type: 'replace',
        payload: {
          editableIndex: payload.editableIndex,
          response,
        },
      });
      if (callback) callback();
    },
    *search({ payload }, { call, put }) {
      const response = yield call(getItemByTitleLike, payload);
      yield put({
        type: 'save',
        payload: response,
      });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    append(state, action) {
      const { list } = state.data;
      list.unshift(action.payload);
      const total = state.data.pagination.total + 1;
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
            total,
          },
        },
      };
    },
    delete(state, action) {
      const { list } = state.data;
      list.splice(action.payload, 1);
      const total = state.data.pagination.total - 1;
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
            total,
          },
        },
      };
    },
    replace(state, action) {
      const { list } = state.data;
      list.splice(action.payload.editableIndex, 1, action.payload.response);
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
          },
        },
      };
    },
  },
};
